import { login, logout, getInfo, getProfession, Registered, GetRegisteredCode, ForgotPassword, Userinformation, UserinfoUpdate, ForgotPasswordNext, UpdatePassword } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { MessageBox, Message } from 'element-ui'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
    PreviousRouter: ""
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token, commit) => {

    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, val) => {

    state.userInfo = val
    sessionStorage.setItem("userInfo", JSON.stringify(val))
  },
  DEL_USERINFO: (state, val) => {
    state.userInfo = {}
    sessionStorage.removeItem("userInfo")
  }
}



const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data, code } = response
        if (code == 200) {
          commit('SET_TOKEN', data)

          setToken(data)
        }
        resolve(response)

      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      Userinformation(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('验证失败，请再次登录.')
        }

        const { userName, realName } = data

        commit('SET_NAME', userName)
        commit('SET_AVATAR', "@/assets/touxiang.png")
        // commit('SET_USERINFO', data)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    commit('RESET_STATE')
    commit('DEL_USERINFO')


    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  //注册
  Registered({ commit }, data) {
    return new Promise((resolve, reject) => {
      Registered(data).then(res => {
        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
  //获取验证码
  ForgotPassword({ commit }, data) {
    return new Promise((resolve, reject) => {
      ForgotPassword(data).then(res => {
        if (res.code === 200) {
          Message.success("短信发送成功！")
        } else {
          Message.error(res.msg)

        }
        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
  //忘记密码-验证手机号，获取验证码-下一步
  verifyCode({ commit }, data) {
    return new Promise((resolve, reject) => {
      ForgotPasswordNext(data).then(res => {

        if (res.code === 200) {
          commit('SET_TOKEN', res.data)
          setToken(res.data)
          // Message.success("短信发送成功！")
        }
        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
  //修改密码
  updatePassword({ commit }, data) {
    return new Promise((resolve, reject) => {
      UpdatePassword(data.data, data.token).then(res => {
        if (res.code === 200) {
          // Message.success(msg || "密码修改成功")
        } else {
          Message.error(res.msg || "密码修改失败")

        }
        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
  //修改个人信息
  updateUserinfo({ commit }, data) {
    return new Promise((resolve, reject) => {
      UserinfoUpdate(data).then(res => {

        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
  //用户注册-验证手机号，获取验证码
  getRegisteredCode({ commit }, data) {
    return new Promise((resolve, reject) => {
      GetRegisteredCode(data).then(res => {

        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
  //所属行业
  getProfession({ commit }, data) {
    return new Promise((resolve, reject) => {
      getProfession(data).then(res => {

        resolve(res)
      }).catch(error => {

        reject(error)
      })
    })
  },
}
const getters = {
  GET_USERINFO: (state) => {
    if (Object.keys(state.userInfo).length == 0) {
      state.userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
    }

    return state.userInfo
  },
}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}

